import {createSlice,createAsyncThunk} from '@reduxjs/toolkit'
import { userLogin } from '../../api/user'

// 【2】定义异步action
export const loginAsync = createAsyncThunk('user/loginAsync',async({values,navigate})=>{
  console.log('登录异步action',values,navigate);
  let res = await userLogin(values)
  navigate('/admin')
  return res.data  //将用户信息传给fulfilled处理函数
})
let initialState = {
  isLogin:false,
  isLoading:false,
  userInfo:null
}
// 尝试提取本地存储用户信息，刷新后保持登录状态
let info = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
if(info){
  initialState.isLogin = true
  initialState.userInfo = JSON.parse(info)
}
const userSlice = createSlice({
  name:'user',
  initialState,
  reducers:{
    loginStart(state){
      state.isLoading = true
    },
    loginSuccess(state,{payload}){ //更新本地交互需要的用户信息
      state.isLoading = false
      state.isLogin = true
      state.userInfo = payload
      console.log(payload);
      localStorage.setItem('userInfo',JSON.stringify(payload))
    },
    loginFail(state){ //退出登录
      state.isLoading = false
      state.isLogin = false
      state.userInfo = null
      localStorage.removeItem('userInfo')
    }
  },
  extraReducers(builder){ //【3】在slice中集成异步action
    builder
    .addCase(loginAsync.pending,(state)=>{ //开始登录
      state.isLoading = true
      console.log('开始登录了');
    })
    .addCase(loginAsync.fulfilled,(state,{payload,meta})=>{ //登录成功,此处的payload是登录成功后，后端下发的用户信息
      state.isLoading = false
      state.isLogin = true
      state.userInfo = payload
      let {remember} = meta.arg.values
      if(remember){
        localStorage.setItem('userInfo',JSON.stringify(payload)) //记住密码
      }else{
        sessionStorage.setItem('userInfo',JSON.stringify(payload)) //未勾选记住密码
      }
      console.log('登录成功',payload,meta);
    })
    .addCase(loginAsync.rejected,(state)=>{ //登录失败
      state.isLoading = false
      state.isLogin = false
      state.userInfo = null
      console.log('登录失败');
    })
  }
})

export const {loginStart,loginSuccess,loginFail} = userSlice.actions
export default userSlice.reducer